<template>
  <Upload 
          action="//jsonplaceholder.typicode.com/posts/"
          :before-upload="onBeforeUpload"
          :show-upload-list="false"
          :maxSize="maxSize"
          :accept="accept"
          :disabled="disabled"
          
          >
    <slot></slot>
  </Upload>
</template>

<script>
export default {
  name: 'cus-upload',
  props: {
    autoUpload: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      // excel -> application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel
      // zip -> application/zip
      default: ''
    },
    maxSize: {
      type: Number,
      default: 12048
    },
    uploadFnc: {
      type: Function,
      default: () => {
      }
    },
    fileName: {
      type: String,
      default: 'file'
    },
    cusParams: {
      type: Object,
      default: () => {
        return {}
      }
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  mounted () {
    this.onBeforeUpload()
  },
  methods: {
    onBeforeUpload (file) {
      if (file && this.autoUpload) {
        this.$emit('onBeforeUpload', file)
        this.$cu.showLoading()
        let params = new FormData()
        for (const key in this.cusParams) {
          params.append(key, this.cusParams[key])
        }
        params.append(this.fileName, file)
        params.append('image', file)
        this.uploadFnc(params).then(res => {
          if (res.code === 1 || res.retCode === 2000) {
            this.$cu.hideLoading()
            this.$Message.success('文件上传成功')
            this.$emit('onOk', res)
          } else{
            //  this.$Message.error(res.retMsg || res.msg)
             this.$emit('onError', res)
             this.$cu.hideLoading(1.5)
          }
        }).catch(() => this.$cu.hideLoading(1.5))
      } else if (file) this.$emit('onBeforeUpload', file)
      return false
    }
  }
}
</script>

<style scoped>

</style>
